package com.cskaoyan.transfer;

import com.cskaoyan.utils.JDBCUtils;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.sql.Statement;

/**
 * 创建日期: 2022/10/10 10:02
 *
 * @author ciggar
 *
 * 转账的案例
 */
public class TransferDemo {

    public static void main(String[] args) throws SQLException {


        Boolean ret = transfer("风华哥","长风",1000);

        if (ret) {
            System.out.println("转账成功！");
        }else {
            System.out.println("转账失败！");
        }

    }


    // 转账的方法
    /**
     * 创建日期：2022/10/10 10:04
     * @param fromName  转账发起人
     * @param toName    转账受益人
     * @param money     转账金额
     * @return boolean
     * @author ciggar
     */
    public static  boolean transfer(String fromName,String toName,Integer money) throws SQLException {

        // 获取连接
        Connection connection = JDBCUtils.getConnection();

        // 开启事务
        connection.setAutoCommit(false);
        Boolean ret = false;

        try {

            // 1. 给转账发起人的账户扣钱
            PreparedStatement decreaseStatement = connection.prepareStatement("update account set money = money - ? where name = ?");

            decreaseStatement.setInt(1, money);
            decreaseStatement.setString(2, fromName);

            int affectedRows = decreaseStatement.executeUpdate();

            if (affectedRows < 1) {
                throw new RuntimeException("扣钱失败！");
            }


            int i = 1/0;

            // 2. 给转账受益人的账户加钱

            PreparedStatement addStatement = connection.prepareStatement("update account set money = money + ? where name = ?");

            addStatement.setInt(1, money);
            addStatement.setString(2, toName);

            int affectedRows2 = addStatement.executeUpdate();



            // 假如扣钱和加钱的操作 都成功，那么提交事务
            // 假如有一个不成功，那么回滚事务
            if (affectedRows > 0 && affectedRows2 > 0) {
                connection.commit();
                ret = true;
            }else {
                throw new RuntimeException("执行失败！进入回滚!");
            }

        }catch (Exception ex) {
            ex.printStackTrace();
            connection.rollback();
            ret = false;
    }

        return ret;
    }
}
